package com.yy.ehcache;



import java.util.concurrent.TimeUnit;

import org.ehcache.Cache;
import org.ehcache.CacheManager;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 自定义缓存
 */
public class Ehcache {
	
	private CacheManager cacheManager;
	private static final Logger logger = LoggerFactory.getLogger(Ehcache.class);
	private CacheConfiguration<String, String> cacheConfiguration;
	private Cache<String, String> myCache;
	
	@SuppressWarnings("unchecked")
    public void setupCache() {
		// 构建一个缓存管理器
		cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);
		// cacheConfiguration -100个换成最大，缓存过期时间10秒
		cacheConfiguration = CacheConfigurationBuilder
				.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(100))
				.withExpiry(Expirations.timeToLiveExpiration(Duration.of(86400, TimeUnit.SECONDS))).build();
		// 根据配置创建一个缓存容器
		myCache = cacheManager.createCache("myCache", cacheConfiguration);
        logger.info("缓存设置完成");
    }
	
	public String getFromCache(String sky) {
        return myCache.get(sky);
    }
	public void addToCache(String sky,String line) {
		myCache.put(sky, line);
	}
	public void clearCache() {
		myCache.clear();
    }
	public void close() {
		cacheManager.close();
	}
	
}
